import { getTriggerByBizType, manualTrigger } from 'src/modules/connector/api/trigger.js'
import CreateSmartPlanDialog from 'src/modules/smartPlan/list/components/createSmartPlanDialog.vue'
import { getRootWindow } from '@src/util/dom'
import { getRootWindowInitData } from '@src/util/window'
import { hasAuth } from '@src/util/auth'
import { storageSet, storageGet } from '@src/util/storageV2';
import { setServerCach, getServerCach } from '@src/util/serverCach'
import { t } from '@src/locales'

export default {
  name: 'manual-trigger-mixin',
  data() {
    return {
      triggerLoading: false,
      triggerList: [], // 触发器列表数据
      buttonStorageData: {}, // 按钮缓存数据，置顶的按钮可平铺显示
      smartPlanButtonTile: 0, // 智能计划按钮是否平铺
      triggerButtonList: [], // 触发器平铺按钮
      sendMessageButtonTile: 0, // 发送短信按钮是否平铺
      sendEmailButtonTile: 0, // 发送邮件按钮是否平铺
      sendActivityButtonTile: 0, // 发送活动调研按钮是否平铺
      remindButtonTile: 0, // 批量提醒按钮是否平铺
      editButtonTile: 0, // 批量编辑按钮是否平铺
      deleteButtonTile: 0, // 删除按钮是否平铺
      bindCustomerButtonTile: 0, // 关联客户按钮是否平铺
    }
  },
  computed: {
    auth() {
      const rootWindowInitData = getRootWindowInitData()
      return rootWindowInitData?.user?.auth || {}
    },
    // 新建智能计划权限
    hasCreateSmartPlanAuth() {
      return hasAuth(this.auth, 'SMART_PLAN_CREATE')
    },
    // 智能计划灰度
    smartPlanGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.SMART_PLAN || false
    },
    // 是否显示新建智能计划
    isShowCreateSmartPlan() {
      return this.hasCreateSmartPlanAuth && this.smartPlanGray
    },
    triggerGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.TRIGGER || false
    },
    // 上级客户灰度
    parentCustomerGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow?.grayAuth?.CUSTOMER_HIERARCHY || false
    },
  },
  watch:{
    buttonStorageData:{
      handler(newValue) {
        this.smartPlanButtonTile = newValue?.smartPlan?.tile || 0
        this.triggerButtonList = this.getTriggerButtonList()
        this.sendMessageButtonTile = newValue?.sendMessage?.tile || 0
        this.sendEmailButtonTile = newValue?.sendEmail?.tile || 0
        this.sendActivityButtonTile = newValue?.sendActivity?.tile || 0
        this.remindButtonTile = newValue?.remind?.tile || 0
        this.editButtonTile = newValue?.edit?.tile || 0
        this.deleteButtonTile = newValue?.delete?.tile || 0
        this.bindCustomerButtonTile = newValue?.bindCustomer?.tile || 0
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 获取触发器列表
    getTriggerList(params) {
      if (this.triggerGray) {
        getTriggerByBizType(params).then(res => {
          this.triggerList = (res.data || []).map(item => {
            item.type = 'trigger'
            return item
          })
          this.triggerButtonList = this.getTriggerButtonList()
        })
      }
    },
    getTriggerButtonList() {
      return this.triggerList.filter(item => {
        if (this.getButtonTile(item.id)) {
          return true
        }
        return false
      })
    },
    // 手动触发触发器
    handleManualTrigger(triggerId, bizIdList) {
      if (this.triggerLoading) return
      this.triggerLoading = true
      manualTrigger({
        triggerId,
        bizIdList
      }).then(res => {
        this.triggerLoading = false
        let isSucc = res.success || res.succ;
      
        this.$platform.notification({
          type: isSucc ? 'success' : 'error',
          title: isSucc ? t('common.base.tip.operationSuccess') : t('common.base.tip.operationFail'),
          message: !isSucc && res.message
        })
      })
    },
    async getButtonLocalStorageData(module, storageKey) {
      let dataStr = storageGet(storageKey) || '{}';
      if(dataStr === '{}'){
        dataStr = await getServerCach(storageKey, {}, module, storageKey) || {}
        dataStr = JSON.stringify(dataStr)
        storageSet(storageKey, dataStr)
      }
      return JSON.parse(dataStr);
    },
    async saveButtonDataToStorage(module, storageKey, key, value) {
      const data = await this.getButtonLocalStorageData(module, storageKey);
      data[key] = value;
      setServerCach(storageKey, data, module, storageKey)
      storageSet(storageKey, JSON.stringify(data))
    },
    // 平铺按钮
    async tileButton(module, storageKey, key, value) {
      if (value.tile == 1) {
        value.tile = 0
      } else {
        value.tile = 1
      }
      if (this.triggerLoading) return
      this.triggerLoading = true
      await this.saveButtonDataToStorage(module, storageKey, key, value)
      this.triggerLoading = false
      this.buttonStorageData = await this.getButtonLocalStorageData(module, storageKey)
    },
    getButtonTile(key) {
      return this.buttonStorageData[key]?.tile || 0
    },
  },
  components: {
    CreateSmartPlanDialog,
  }
}